package com.saxion.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.saxion.model.Bestelling;
import com.saxion.model.Product;


public class ProductDaoImpl implements ProductDao {

 private SessionFactory sessionFactory;
     
     public SessionFactory getSessionFactory() {return sessionFactory;}

     public void setSessionFactory(SessionFactory sessionFactory) {
         this.sessionFactory = sessionFactory;
     }

	
	@Override
	public Product getProductById(int id) {
		Session session = null;
		try{
			try{
				session = sessionFactory.getCurrentSession();
			}catch(HibernateException e){
				session = sessionFactory.openSession();
			}
			ArrayList<Product> producten = (ArrayList<Product>) session.createQuery("from Product where product_id = ?").setLong(0, id).list();
			if(!producten.isEmpty()){
				return producten.get(0);
			}
		}catch(HibernateException e){
			session = sessionFactory.openSession();
		}finally{
			session.close();
		}
		return null;
	}

	@Override
	public List<Product> getProductBySoort(String soort) {
		Session session = null;
		try{
			try{
				session = sessionFactory.getCurrentSession();
			}catch(HibernateException e){
				session = sessionFactory.openSession();
			}
			ArrayList<Product> producten = new ArrayList<Product>();
			if(soort.isEmpty()){
				producten = (ArrayList<Product>) session.createQuery("from Product").list();
			}else{

				producten = (ArrayList<Product>) session.createQuery("from Product where productSoort = ?").setString(0, soort).list();	
			}
			return producten;
		}catch(HibernateException e){
			e.printStackTrace();
			session = sessionFactory.openSession();
		}finally{
			session.close();
		}
		return new ArrayList<Product>();
	}

	@Override
	public Product addProduct(Product p) {
		Session session = null;
		try{
			session = sessionFactory.getCurrentSession();
		}catch(HibernateException e){
			session = sessionFactory.openSession();
		}
        Transaction tx = null;
        try{
        	if (session.getTransaction() != null
    	            && session.getTransaction().isActive()) {
    	        tx = session.getTransaction();
    	    } else {
    	        tx = session.beginTransaction();
    	    }
			session.save(p);
	        tx.commit();			
        }catch( HibernateException e){
        	if(tx!=null){
        		tx.rollback();
        	}
        	e.printStackTrace();
        }finally{
        	session.close();
        }
        
        return p;

		
	}

}
